/**
 * 
 */
package kr.pe.johnkim.dayve.activity;

import java.io.IOException;
import java.util.List;

import kr.pe.johnkim.dayve.provider.DayveLog;
import kr.pe.johnkim.dayve.rest.DayveCommonRest;
import kr.pe.johnkim.dayve.util.DayveCommon;
import kr.pe.johnkim.dayve.util.ExternalJoinConstant;

import org.json.JSONException;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * Dayve 공지 사항 웹 페이지를 출력하는 클래스 이다.
 * 
 * @author johnkim
 *
 */
public class DayveAnnouncementView extends Activity {

	public static final String TAG = DayveAnnouncementView.class.getSimpleName();
	
	DayveCommonRest dayveCommonRest = new DayveCommonRest();
	DayveCommon dayveCommon = new DayveCommon();
	
	// 현재 시간.
	private String currentDate;
	
	// 사용자 아이디.
	private String DAYVE_ID = "";
	
	WebView mWeb;
	
	ProgressBar progressBarAnnouncement;
	TextView txtViewAnnouncementNotification;

	// 프로그레스 바를 출력 한다.
	private static final int THREAD_PROGRESS_BAR_VISIBLE = 101;

	// 프로그레스 바를 감춘다.
	private static final int THREAD_PROGRESS_BAR_INVISIBLE = 102;
	
	private String WEB_URL = ExternalJoinConstant.WEB_SERVER_URL + ExternalJoinConstant.DAYVE_ANNOUNCEMENT;

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.dayve_announcement);
		
		confirmNotification();
		
		// 현재 시간을 가져 온다.
		currentDate = dayveCommon.getCurrentDate();
		
		progressBarAnnouncement = (ProgressBar)findViewById(R.id.progressBarAnnouncement);
		txtViewAnnouncementNotification = (TextView)findViewById(R.id.txtViewAnnouncementNotification);
		txtViewAnnouncementNotification.setText(R.string.announcement_notification);
		
		mWeb = (WebView)findViewById(R.id.web);
//		mWeb.getSettings().setJavaScriptEnabled(true);
		mWeb.setWebViewClient(new Announcememt());
		WebSettings webSet = mWeb.getSettings();
		webSet.setJavaScriptEnabled(true);
//		webSet.setBuiltInZoomControls(true);
		mWeb.loadUrl(WEB_URL);
	}
	
	/**
	 * SharedPreferences 정보를 확인 한다.
	 */
	public void confirmNotification() {
		String myPf = "kr.pe.johnkim.dayve.activity_preferences";
		SharedPreferences mSharedPreferences = getSharedPreferences(myPf, Activity.MODE_PRIVATE);
		
		// id 를 가져 온다.
		DAYVE_ID = mSharedPreferences.getString("dayve_id", "");

	}
	
	/**
	 * Handler 를 정의한다.
	 * 모든 Thread 를 등록해 놓고 필요할때 호출한다.
	 */
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			// 프로그레스 바를 출력 한다.
			case THREAD_PROGRESS_BAR_VISIBLE : 
				progressBarAnnouncement.setVisibility(View.VISIBLE);
				txtViewAnnouncementNotification.setVisibility(View.VISIBLE);
				break;
			// 프로그레스 바를 감춘다.
			case THREAD_PROGRESS_BAR_INVISIBLE : 
				progressBarAnnouncement.setVisibility(View.INVISIBLE);
				txtViewAnnouncementNotification.setVisibility(View.INVISIBLE);
				break;
			}
		}
	};

	/* (non-Javadoc)
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if ((keyCode == KeyEvent.KEYCODE_BACK) && mWeb.canGoBack()) {
            mWeb.goBack();
            return true;
        }
		
        return super.onKeyDown(keyCode, event);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		// main thread 에서 child thread 를 호출 한다.
		Thread thread = new Thread(null, doBackgroundThreadProcessing, "Background_insertLog");
		thread.start();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
		finish();
	}
	
	/* 최상위 프로세스가 아닐 경우 프로세스를 종료 한다.
	 * 
	 * => Home Key 를 눌렀을때 프로세스를 종료 한다.
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		if(!isForegrdound()) {
			DayvePreferenceView.activity.finish();
			System.exit(0);
		}
	}
	
	/**
	 * 현재 프로세스가 최상위로 실행중인지 검사 한다.
	 * 
	 * true : 최상위
	 * 
	 * @return
	 */
	public boolean isForegrdound() {
	    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	    List<RunningTaskInfo> list = am.getRunningTasks(1);
	    ComponentName cn = list.get(0).topActivity;
	    String name = cn.getPackageName();
	     
	    return name.indexOf(getPackageName()) > -1;
	}
	
	/**
	 * WebViewClient 를 상속하는 클래스이다.
	 *
	 * @author John_Kim <cale9797@gmail.com>
	 *
	 */
	class Announcememt extends WebViewClient {
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}

		/* (non-Javadoc)
		 * @see android.webkit.WebViewClient#onPageFinished(android.webkit.WebView, java.lang.String)
		 */
		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onPageFinished(view, url);

			mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_INVISIBLE));
		}

		/* (non-Javadoc)
		 * @see android.webkit.WebViewClient#onPageStarted(android.webkit.WebView, java.lang.String, android.graphics.Bitmap)
		 */
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			super.onPageStarted(view, url, favicon);

			mHandler.sendMessage(mHandler.obtainMessage(THREAD_PROGRESS_BAR_VISIBLE));
		}
	}
	
	/**
	 * 로그를 저장 한다.
	 */
	private void insertLog() {
		Log.i(TAG, "insertLog");
		
		DayveLog dayveLog = new DayveLog();
		
		dayveLog.setId(DAYVE_ID);
		dayveLog.setViewName(TAG);
		dayveLog.setAccessDate(currentDate);
		
		try {
			dayveCommonRest.registerLog(dayveLog);
			Log.i(TAG, "Success to insert log.");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, "Fail to insert log.");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e(TAG, "Fail to insert log.");
		}
	}
	
	/**
	 * 로그 저장은 UI 와 관계 없기 때문에 background thread 로 구현 함 : child thread
	 */
	private Runnable doBackgroundThreadProcessing = new Runnable() {
		
		public void run() {
			// TODO Auto-generated method stub
			insertLog();
		}
	};
}
